package com.banban.user.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import java.util.Base64;

public class TripleDESUtil {
    private static final String SECRET_KEY = "123456789012345678901234";
    private static final String ALGORITHM = "DESede";

    /**
     * 加密
     * @param plainText 明文
     * @param secretKey 密钥（长度必须为24位）
     * @return 加密后的字符串
     * @throws Exception
     */
    public static String encrypt(String plainText, String secretKey) throws Exception {
        // 创建密钥规范
        KeySpec keySpec = new DESedeKeySpec(secretKey.getBytes(StandardCharsets.UTF_8));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey key = keyFactory.generateSecret(keySpec);

        // 创建 Cipher
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);

        // 加密数据
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 解密
     * @param encryptedText 密文
     * @param secretKey 密钥（长度必须为24位）
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decrypt(String encryptedText, String secretKey) throws Exception {
        // 创建密钥规范
        KeySpec keySpec = new DESedeKeySpec(secretKey.getBytes(StandardCharsets.UTF_8));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey key = keyFactory.generateSecret(keySpec);

        // 创建 Cipher
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);

        // 解密数据
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }


    public static void main(String[] args) throws Exception {
        String plainText = "123123";
        String secretKey = "OtiMcTkYGgkKlOIdJooGNEDF"; // 密钥长度必须为24位

        // 加密
        String encryptedText = TripleDESUtil.encrypt(plainText, secretKey);
        System.out.println("Encrypted Text: " + encryptedText);

        // 解密
        String decryptedText = TripleDESUtil.decrypt(encryptedText, secretKey);
        System.out.println("Decrypted Text: " + decryptedText);

        // 解密
        String decryptedText2 = TripleDESUtil.decrypt("/nHXaVvUCo3bDa0NPhmZcg==", secretKey);
        System.out.println("Decrypted Text: " + decryptedText2);

    }
}